<template>
    <view class="comm-list-container">
        <!-- 使用封装的页面头部组件 -->
        <page-header title="采收管理"></page-header>

        <!-- 搜索框 -->
        <view class="search-box">
            <uni-search-bar
                v-model="searchKeyword"
                placeholder="请输入要搜索的作物内容"
                @confirm="handleSearch"
                @input="handleSearch"
                :radius="100"
                cancelButton="none" />
        </view>

        <!-- 过滤选项卡 -->
        <filter-tabs :activeTab="activeTab" @tab-change="handleFilterChange" />

        <!-- 采收记录列表 -->
        <view class="comm-record-list" v-if="harvestList.length > 0">
            <record-item
                v-for="item in harvestList"
                :key="item.id"
                :item="item"
                @clickItem="viewDetail(item)"
                @edit="editHarvest(item.id)"
                @delete="confirmDeleteHarvest(item.id)">
                <template #header>
                    <view class="item-header">
                        <view style="display: flex; align-items: center">
                            <image
                                style="margin-right: 10rpx"
                                class="icon-wrapper"
                                src="/static/images/caishou.png"
                                mode="aspectFill"></image>
                            <text class="date-title">{{ item.fieldName }}条田</text>
                        </view>

                        <text class="date-small">
                            {{ formatDate(item.startDate || item.createTime) }}
                        </text>
                    </view>
                </template>

                <template #content>
                    <view class="item-content">
                        <view class="info-row">
                            <view class="info-label">水稻类型:</view>
                            <view class="info-value">
                                {{ getCropName(item.cropType, item.cropVarietyId) }}
                            </view>

                            <view class="info-label" style="margin-left: 40rpx">面积:</view>
                            <view class="info-value">{{ item.area }} 亩</view>

                            <view class="info-label" style="margin-left: 40rpx">净重:</view>
                            <view class="info-value">{{ item.netWeight }} kg</view>
                        </view>

                        <!-- <view class="info-row">
                            <view class="info-label">处理方案:</view>
                            <view class="info-value">{{ item.remarks || '暂无说明' }}</view>
                        </view> -->
                        <view class="info-row">
                            <text class="info-label">备注</text>
                            <text class="info-value">{{ item.remark }}</text>
                        </view>
                        <view class="item-images" v-if="item.images">
                            <image
                                v-for="(img, imgIndex) in formatImages(item.images).slice(0, 2)"
                                :key="imgIndex"
                                :src="img"
                                mode="aspectFit"></image>
                        </view>
                        <view class="info-columns" style="gap: 10rpx">
                            <view class="info-tag1">
                                成熟度
                                {{ item.maturityLevel || '' }}
                            </view>

                            <view class="info-tag2">损耗{{ item.lossRate || '' }}</view>

                            <view class="info-tag3">
                                等级
                                {{
                                    getDictLabel(
                                        'harvesting_management_level',
                                        item.qualityGrade
                                    ) || ''
                                }}
                            </view>
                        </view>
                    </view>
                </template>
            </record-item>

            <!-- 加载更多提示 -->
            <view class="load-more-container" v-if="harvestList.length > 0">
                <view v-if="loadingMore" class="loading-more">
                    <text class="loading-text">加载中...</text>
                </view>
                <view v-else-if="!hasMore" class="no-more">
                    <text class="no-more-text">没有更多数据了</text>
                </view>
            </view>
        </view>
        <!-- 空数据展示 -->
        <empty-data
            v-if="harvestList.length === 0 && !loading"
            tip="暂无采收记录"
            btnText="添加采收记录"
            @click="navigateToAdd" />
        <!-- 添加按钮 -->
        <view class="add-button" @click="navigateToAdd">
            <text class="add-icon">+</text>
        </view>
    </view>
</template>

<script>
import PageHeader from '@/components/PageHeader/index.vue'
import FilterTabs from '@/components/FilterTabs/index.vue'
import RecordItem from '@/components/RecordItem/index.vue'
import EmptyData from '@/components/EmptyData/index.vue'
import { harvest } from '@/utils/api/index.js'
import { formatDateChinese, formatImages } from '@/utils/util.js'
import { mapGetters, mapActions } from 'vuex'

export default {
    components: {
        PageHeader,
        FilterTabs,
        RecordItem,
        EmptyData,
    },
    data() {
        return {
            searchKeyword: '',
            loading: false,
            loadingMore: false, // 加载更多状态
            hasMore: true, // 是否还有更多数据
            activeTab: 'all',
            harvestList: [],
            // 分页参数
            pageParams: {
                pageNo: 1,
                pageSize: 30,
                total: 0,
            },
        }
    },
    computed: {
        ...mapGetters({
            getDictByType: 'getDictByType',
            getDictLabel: 'getDictLabel',
        }),
    },
    onLoad() {
        // 确保字典数据已加载
        this.loadDictData()
    },
    onShow() {
        this.loadHarvestRecords()
    },
    onPullDownRefresh() {
        this.loadHarvestRecords()
    },
    onReachBottom() {
        this.loadMoreData()
    },
    methods: {
        ...mapActions(['getDictByType']),

        // 加载字典数据
        async loadDictData() {
            try {
                // 加载作物类型字典
                await this.getDictByType('crop_name_type')

                // 预加载各种作物的品种字典
                const cropTypes = this.getDictByType('crop_name_type')
                for (const crop of cropTypes) {
                    if (crop.value) {
                        await this.getDictByType(crop.value)
                    }
                }
            } catch (error) {
                console.error('加载字典数据失败:', error)
            }
        },

        // 获取作物名称和品种的显示文本
        getCropName(cropType, cropVarietyId) {
            if (!cropType) return '未指定'

            const cropLabel = this.getDictLabel('crop_name_type', cropType) || cropType
            let varietyLabel = cropVarietyId || ''

            // 如果有作物类型，尝试从对应的品种字典中获取品种名称
            if (cropType && cropVarietyId) {
                varietyLabel = this.getDictLabel(cropType, cropVarietyId) || cropVarietyId
            }

            if (cropLabel && varietyLabel) {
                return `${cropLabel}-${varietyLabel}`
            } else if (cropLabel) {
                return cropLabel
            } else if (varietyLabel) {
                return varietyLabel
            }

            return '未指定'
        },

        // 处理筛选变化
        handleFilterChange(tabValue, filterData) {
            this.activeTab = tabValue

            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 清除之前的日期和地块筛选条件
            delete this.pageParams.startDate
            delete this.pageParams.endDate
            delete this.pageParams.plotId
            delete this.pageParams.fieldId

            // 添加新的筛选条件
            if (filterData) {
                if (filterData.startDate && filterData.endDate) {
                    this.pageParams.startDate = filterData.startDate
                    this.pageParams.endDate = filterData.endDate
                }

                if (filterData.areaId) {
                    this.pageParams.plotId = filterData.areaId
                }
            }

            // 重新请求接口
            this.loadHarvestRecords()
        },

        // 处理搜索变化
        handleSearch(e) {
            // 重置页码
            this.pageParams.pageNo = 1
            this.hasMore = true // 重置加载更多状态

            // 更新关键词搜索参数
            if (this.searchKeyword) {
                this.pageParams.cropName = e || this.searchKeyword
            } else {
                delete this.pageParams.cropName
            }

            // 重新请求接口
            this.loadHarvestRecords()
        },

        // 加载采收记录
        async loadHarvestRecords(isLoadMore = false) {
            try {
                if (isLoadMore) {
                    this.loadingMore = true
                } else {
                    this.loading = true
                    uni.showLoading({ title: '加载中...' })
                }

                const res = await harvest.getHarvestList(this.pageParams)
                console.log('返回数据')
                console.log(res)
                if (res.code === 0 && res.data) {
                    // 处理图片数据，将JSON字符串转为数组
                    const newList = res.data.list || []

                    if (isLoadMore) {
                        // 加载更多时追加数据
                        this.harvestList = [...this.harvestList, ...newList]
                    } else {
                        // 首次加载或刷新时替换数据
                        this.harvestList = newList
                    }

                    // 判断是否还有更多数据
                    this.hasMore = newList.length >= this.pageParams.pageSize
                    this.pageParams.total = res.data.total
                } else {
                    if (!isLoadMore) {
                        uni.showToast({
                            title: res.msg || '加载失败',
                            icon: 'none',
                        })
                    }
                }
            } catch (error) {
                console.error('加载采收记录失败:', error)
                if (!isLoadMore) {
                    uni.showToast({
                        title: '加载失败',
                        icon: 'none',
                    })
                }
            } finally {
                this.loading = false
                this.loadingMore = false
                uni.hideLoading()
                uni.stopPullDownRefresh()
            }
        },

        // 预览图片
        previewImage(images, current) {
            uni.previewImage({
                urls: images,
                current: images[current],
            })
        },

        // 查看详情
        viewDetail(item) {
            uni.navigateTo({
                url: `/pages/agriculture/harvestManagement/addHarvest?id=${item.id}`,
            })
        },

        // 编辑采收记录
        editHarvest(id) {
            uni.navigateTo({
                url: `/pages/agriculture/harvestManagement/addHarvest?id=${id}`,
            })
        },

        // 确认删除采收记录
        confirmDeleteHarvest(id) {
            uni.showModal({
                title: '确认删除',
                content: '确定要删除这条采收记录吗？',
                success: async (res) => {
                    if (res.confirm) {
                        await this.deleteHarvest(id)
                    }
                },
            })
        },

        // 删除采收记录
        async deleteHarvest(id) {
            try {
                uni.showLoading({ title: '删除中...' })

                const res = await harvest.deleteHarvest(id)

                if (res.code === 0) {
                    // 删除成功，更新列表
                    const index = this.harvestList.findIndex((item) => item.id === id)
                    if (index !== -1) {
                        this.harvestList.splice(index, 1)
                    }

                    uni.showToast({
                        title: '删除成功',
                        icon: 'success',
                    })
                } else {
                    uni.showToast({
                        title: res.msg || '删除失败',
                        icon: 'none',
                    })
                }
            } catch (error) {
                console.error('删除采收记录失败:', error)
                uni.showToast({
                    title: '删除失败',
                    icon: 'none',
                })
            } finally {
                uni.hideLoading()
            }
        },

        // 跳转到添加页面
        navigateToAdd() {
            uni.navigateTo({
                url: '/pages/agriculture/harvestManagement/addHarvest',
            })
        },

        // 格式化日期
        formatDate(dateString) {
            return formatDateChinese(dateString)
        },

        // 格式化图片
        formatImages(imagesStr) {
            return formatImages(imagesStr)
        },

        // 加载更多数据
        async loadMoreData() {
            if (this.loadingMore || !this.hasMore) {
                return
            }

            this.pageParams.pageNo += 1
            await this.loadHarvestRecords(true)
        },
    },
}
</script>

<style lang="scss">
.info-tag1 {
    padding: 10rpx 20rpx;
    background: rgba(15, 214, 91, 0.2);
    font-size: 24rpx;
    color: rgba(15, 214, 91, 1);
    border-radius: 4rpx;
}
.info-tag2 {
    padding: 10rpx 20rpx;
    background: rgba(237, 21, 21, 0.3);
    font-size: 24rpx;
    color: rgba(237, 21, 21, 1);
    border-radius: 4rpx;
}
.info-tag3 {
    padding: 10rpx 20rpx;
    background: rgba(39, 21, 237, 0.3);
    font-size: 24rpx;
    color: rgba(39, 21, 237, 1);
    border-radius: 4rpx;
}
</style>
